package com.wasin.server.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.diboot.core.vo.JsonResult;
import com.wasin.server.util.CaptchaUtils;
import com.wasin.server.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ 作者： wasin
 * @ 创建时间： 2021/9/18  10:26
 * @ 说明：    验证码
 * @ 当前版本:  1.0.0
 */
@Api(tags = {"验证码"})
@RestController
public class CaptchaController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CaptchaUtils captchaUtils;


    @ApiOperation(value = "获取图形验证码")
    @GetMapping("getCaptcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        //设置response响应
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //把验证码凭证放到header captcha中
        String tokenId = UUID.randomUUID().toString();
        response.setHeader("captcha",tokenId);
        LineCaptcha captCha = captchaUtils.getCaptCha(tokenId,60);
        //输出浏览器
        OutputStream out=response.getOutputStream();
        captCha.write(out);
        out.flush();
        out.close();
    }

    @ApiOperation(value = "校验图形验证码")
    @PostMapping("verifyCaptcha")
    public JsonResult<Boolean> verifyCaptcha(HttpServletRequest request,String code){
        String captcha = request.getHeader("captcha");
        return JsonResult.OK(captchaUtils.verifyCaptcha(captcha,captcha));
    }

    @ApiOperation(value = "获取二维码")
    @GetMapping("getQrCode")
    public void getQrCode(HttpServletResponse response,String content) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        BufferedImage image = QrCodeUtil.generate(content, 300, 300);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"png",out);
        out.flush();
        out.close();
    }

}
